package net.maergaiyun.func;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.maergaiyun.util.TimeUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;

@Slf4j
public class UniqueVisitorFilterFunction extends RichFilterFunction<JSONObject> {
    private ValueState<String> lastVisitDateState = null;

    @Override
    public void open(Configuration parameters) throws Exception {
        ValueStateDescriptor<String> visitDateStateDes = new ValueStateDescriptor<>("visitDateState", String.class);

        StateTtlConfig stateTtlConfig = StateTtlConfig.newBuilder(Time.days(1)).build();

        visitDateStateDes.enableTimeToLive(stateTtlConfig);
        this.lastVisitDateState = getRuntimeContext().getState(visitDateStateDes);
    }

    @Override
    public void close() throws Exception {
        super.close();
    }

    @Override
    public boolean filter(JSONObject jsonObject) throws Exception {
        // 获取当前访问时间
        Long visitTime = jsonObject.getLong("visitTime");
        String udid = jsonObject.getString("udid");


        String currentVisitDate = TimeUtil.format(visitTime);
        // 上次状态访问时间
        String lastVisitDate = lastVisitDateState.value();

        if (StringUtils.isNotBlank(lastVisitDate) && lastVisitDate.equalsIgnoreCase(currentVisitDate)) {
            System.out.println("udid=" + udid + "已经在" + lastVisitDate + "时间访问过");
            return false;

        } else {
            System.out.println("udid=" + udid + "在" + currentVisitDate + "时间初次访问");
            lastVisitDateState.update(currentVisitDate);
            return true;
        }
    }
}
